import relationalStore from '@ohos.data.relationalStore'; // 导入模块
import UIAbility from '@ohos.app.ability.UIAbility';

export function queryMachineID(context,callback: (err: Error | null, machineID: string) => void) {
  const STORE_CONFIG = {
    name: 'Config.db',
    securityLevel: relationalStore.SecurityLevel.S1
  };

  // 初始化数据库存储
  relationalStore.getRdbStore(context, STORE_CONFIG, (err, store) => {
    if (err) {
      //console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`);
      callback(err, `Failed to get RdbStore. Code:${err.code}, message:${err.message}`);
      return;
    }
    console.info(`Succeeded in getting RdbStore.`);

    // 创建查询条件
    const predicates = new relationalStore.RdbPredicates('config');

    // 执行查询
    store.query(predicates, ['MachineID'], (err, resultSet) => {
      if (err) {
        //console.error(`Failed to query data. Code:${err.code}, message:${err.message}`);
        callback(err, `Failed to query data. Code:${err.code}, message:${err.message}`);
        return;
      }

      if (resultSet.rowCount > 0) {
        // 如果有数据，只返回第一行
        resultSet.goToFirstRow();
        const machineID = resultSet.getString(0);
        callback(null, machineID);
        resultSet.close();
      } else {
        let machineID = this.generateMachineID();
        //let machineID = 'test123';
        // 插入新数据
        //const insertSql = 'INSERT INTO config (MachineID) VALUES (?)';
        const valueBucket = {
          'MachineID': machineID,
        };
        //const insertData = [machineID];
        store.insert('config', valueBucket, (insertErr) => {
          if (insertErr) {
            //console.error(`Failed to insert data. Code:${insertErr.code}, message:${insertErr.message}`);
            callback(insertErr, `Failed to insert data. Code:${insertErr.code}, message:${insertErr.message}`);
          } else {
            console.log(`Data inserted successfully.`);
            callback(null, machineID);
          }
          // 如果之前没有关闭结果集，可以在这里关闭
          resultSet.close();
        });
      }
    });
  });
}

export function generateMachineID() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要+1
  const date = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  const milliseconds = String(now.getMilliseconds()).padStart(3, '0');
  const formattedTime = `${year}${month}${date}${hours}${minutes}${seconds}${milliseconds}`;
  const randomSuffix = Math.floor(Math.random() * 100).toString().padStart(2, '0'); // 生成00-99的随机数并填充为两位数
  return formattedTime + randomSuffix;
  //return 'test1011';
}

export function initRdbStore(context) {
  const STORE_CONFIG = {
    name: 'Config.db', // 数据库文件名
    securityLevel: relationalStore.SecurityLevel.S1 // 数据库安全级别
  };
  const createTableSql = 'CREATE TABLE IF NOT EXISTS config (MachineID)'; // 建表Sql语句

  //this.initRdbStore(STORE_CONFIG, SQL_CREATE_CONFIG_TABLE);

  relationalStore.getRdbStore(context, STORE_CONFIG, (err, store) => {
    if (err) {
      console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`);
      return;
    }
    console.info(`Succeeded in getting RdbStore.`);
    //let machineID = formattedTime;
    let machineID = generateMachineID();
    //let machineID = 'test123';
    // 插入新数据
    //const insertSql = 'INSERT INTO config (MachineID) VALUES (?)';
    const valueBucket = {
      'MachineID': machineID,
    };
    // 创建数据表
    store.executeSql(createTableSql);
    store.insert('config', valueBucket, (insertErr) => {
      if (insertErr) {
        return console.error(`Failed to insert data. Code:${insertErr.code}, message:${insertErr.message}`);
        //callback(insertErr, `Failed to insert data. Code:${insertErr.code}, message:${insertErr.message}`);
      } else {
        return `Data inserted successfully.`;
        //callback(null, machineID);
      }
      // 如果之前没有关闭结果集，可以在这里关闭
      //resultSet.close();
    });
    //return store;
    // 在这里你可以调用查询方法或其他数据库操作
    //queryMachineID(store);
  });
}

export function deleteDB(context,callback: (err: Error | null, machineID: string) => void) {
  relationalStore.deleteRdbStore(context, 'Config.db', (err) => {
    if (err) {
      callback(null,`Failed to delete RdbStore. Code:${err.code}, message:${err.message}`);
    }
    callback(null,'Succeeded in deleting RdbStore.');
  });
}